package com.leef.createPay.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;



@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="localContainerEntityManagerFactoryBeanTwo",
        transactionManagerRef = "platformTransactionManagerTwo",
        basePackages = {"com.leef.createPay.dao.two"}
)
public class JpaConfigTwo {

    @Resource(name = "db2")
    DataSource ds2;
    @Autowired
    JpaProperties jpaProperties;


    @Bean("entityManagerTwo")
    @Primary
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return localContainerEntityManagerFactoryBeanTwo(builder).getObject().createEntityManager();
    }



    @Bean(name = "localContainerEntityManagerFactoryBeanTwo")
    public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBeanTwo
            (EntityManagerFactoryBuilder builder) {
        return builder.dataSource(ds2)
                .properties(jpaProperties.getProperties())
                .packages("com.leef.createPay.domain.two")
                .persistenceUnit("pu2")
                .build();
    }

    @Bean(name = "platformTransactionManagerTwo")
    public PlatformTransactionManager platformTransactionManagerTwo(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(localContainerEntityManagerFactoryBeanTwo(builder).getObject());
    }

}
